package helloworld.dao.administrate;

import helloworld.entity.administrate.Role;
import helloworld.entity.administrate.User;
import helloworld.modules.hibernate.HibernateDao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Repository;

@Repository
public class UserDao extends HibernateDao<User, Long> {

	public void save(User entity, List<Long> checkedRoleIds) {
		if (checkedRoleIds == null || checkedRoleIds.size() == 0) {
			entity.setRoleList(new ArrayList<Role>());
		} else {
			Iterator<Role> iterator = entity.getRoleList().iterator();
			while (iterator.hasNext()) {
				Role role = iterator.next();
				if (checkedRoleIds.contains(role.getId())) {
					checkedRoleIds.remove(role.getId());
				} else {
					iterator.remove();
				}
			}
			for (Long id : checkedRoleIds) {
				Role role = new Role();
				role.setId(id);
				entity.getRoleList().add(role);
			}
		}

		this.save(entity);
	
	}

}
